package cn.hicard.risk.action.bd;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import cn.hicard.risk.common.Constant;
import cn.hicard.risk.entity.BdPeriodfreeze;
import cn.hicard.risk.report.ReportTemplet;
import cn.hicard.risk.service.bd.PeriodFreezeService;
import cn.hicard.util.DateHelp;

public class PeriodFreezeFlex {

	
	/** 日志记录工具 */
	private static Logger logger = Logger.getLogger(Constant.LOGGER_MAIN);
	
	/** 周期冻结业务类*/
	private PeriodFreezeService periodFreezeService;
	
	public void setPeriodFreezeService(PeriodFreezeService periodFreezeService) {
		this.periodFreezeService = periodFreezeService;
	}


	/**
	 * 查询T+2商户冻结报表
	 * @param start
	 * @param end
	 * @return
	 * @throws Exception 
	 */
	public List<BdPeriodfreeze> findFreezeReport(BdPeriodfreeze start, BdPeriodfreeze end) throws Exception{
		//1.只要是需要调单的数据
		//2.限制交易日期
		try {
			//已冻结的
			start.setIsfreeze("0");
			return periodFreezeService.findList(start, end);
		} catch (Exception e) {
			logger.error("查询T+2商户冻结报表出错", e);
			throw e;
		}
	}
	
	
	/**
	 * 下载T+2商户冻结报表
	 * @param start
	 * @param end
	 * @return
	 */
	public byte[] downloadFreezeReport(BdPeriodfreeze start, BdPeriodfreeze end){		
		
		// 根据冻结信息的创建时间
		// 查询出需要冻结的数据
		List<BdPeriodfreeze> freezeList = null;
		try {
			freezeList = findFreezeReport(start, end);
		} catch (Exception e) {
			logger.error("",e);
		}
		if(freezeList == null){
			freezeList = new  ArrayList<BdPeriodfreeze>();
		}
		
		// 构建报表
		ReportTemplet rt = new ReportTemplet();
		
		String title = "风控T+2商户传统pos冻结报表";
		String descrip = "条件：共计 " 
							  + freezeList.size() 
							  + " 条，报表下载开始时间： " + start.getTransdate() 
							  + "，  报表下载结束时间： " + end.getTransdate();
		
		String[] fields = new String[]{"汇卡商户号","商户名称","订单号","系统参考号","交易时间","冻结时间","交易金额（单位/元）","业务类型","清算周期"};
		List<Object[]> source = new ArrayList<Object[]>();		
		// 组装数据
		for (BdPeriodfreeze item:freezeList) {			
			source.add(new Object[]{
					item.getWpmerchno(), 
					item.getMerchname(),
					item.getOrderno(),
					item.getSysno(),
					DateHelp.numberToDate(item.getTransdate() + item.getTranstime().substring(4)),
					item.getProcdate()==null?"":item.getProcdate(),
					item.getTransmoney(),
					item.getCallflag(),
					item.getPeriod()
					});
		}
		
		ByteArrayOutputStream bos = rt.createGeneralTemplet(title, descrip, fields, source);
		return bos.toByteArray();
	}
	
	
	/**
	 * 查询风控T+2商户解冻报表
	 * @param start
	 * @param end
	 * @return
	 * @throws Exception
	 */
	public List<BdPeriodfreeze> findUnfreezeReport(BdPeriodfreeze start, BdPeriodfreeze end) throws Exception{
		//1.已解冻的
		start.setIsfreeze("1");
		//2.限制处理日期 // 格式处理
		//start.setProcdate(start.getProcdate() + " 00:00:00");
		//end.setProcdate(end.getProcdate() + " 23:59:59");	
		try {
			List<BdPeriodfreeze> list = periodFreezeService.findList(start, end);
			return list;
		} catch (Exception e) {
			logger.error("查询T+2商户解冻报表出错", e);
			throw e;
		}
	}
	
	/**
	 * 下载风控T+2商户解冻报表
	 * @param start
	 * @param end
	 * @return
	 */
	public byte[] downloadUnfreezeReport(BdPeriodfreeze start, BdPeriodfreeze end){
		// 查询出调单管理数据
		List<BdPeriodfreeze> freezeList = null;
		try {
			freezeList = findUnfreezeReport(start, end);
		} catch (Exception e) {
			logger.error("",e);
		}
		if(freezeList == null){
			freezeList = new  ArrayList<BdPeriodfreeze>();
		}
		
		// 构建报表
		ReportTemplet rt = new ReportTemplet();
		
		String title = "风控T+2商户传统pos解冻报表";
		String descrip = "条件：共计 " 
							  + freezeList.size() 
							  + " 条，报表下载开始时间： " + start.getProcdate() 
							  + "，  报表下载结束时间： " + end.getProcdate();
		
		String[] fields = new String[]{"汇卡商户号","商户名称","订单号","系统参考号","交易时间","处理时间","交易金额（单位/元）","业务类型","清算周期"};
		List<Object[]> source = new ArrayList<Object[]>();		
		// 组装数据
		for (BdPeriodfreeze item:freezeList) {			
			source.add(new Object[]{
					item.getWpmerchno(), 
					item.getMerchname(),
					item.getOrderno(),
					item.getSysno(),
					DateHelp.numberToDate(item.getTransdate() + item.getTranstime().substring(4)),
					item.getProcdate(),
					item.getTransmoney(),
					item.getCallflag(),
					item.getPeriod()
					});
		}
		
		ByteArrayOutputStream bos = rt.createGeneralTemplet(title, descrip, fields, source);
		return bos.toByteArray();
	}
	
	
	/**
	 * 解冻宁波周期冻结的交易
	 * T+2
	 * @param date
	 * @return
	 * @throws Exception 
	 */
	public void doUnFreeeze() throws Exception{
		
		// 前一天
		String yesterday = DateHelp.format(new Date(System.currentTimeMillis() - 24*60*60*1000), "yyyyMMdd");
		
		// 最后交易日期
		String lastdate = "";
		try {
            //createdate
			List<String> list = periodFreezeService.findLastDate(DateHelp.date());
			
			if(list == null || list.size() == 0 || list.get(0) == null){
				logger.warn("查询上一工作日日期为空，默认使用系统当前日期的前一天:" + yesterday);				
				lastdate = yesterday;
			}else{
				//只取yyyy-MM-dd
				lastdate = list.get(0).toString().substring(0, 10); 
			}
		} catch (Exception e) {
			logger.error("查询上一工作日日期时出错", e);
		}
		
		//再调一个方法统计总解冻数据量
		BdPeriodfreeze start = new BdPeriodfreeze();
		BdPeriodfreeze end = new BdPeriodfreeze();
		start.setCreatedate(lastdate + " 00:00:00");
		end.setCreatedate(lastdate + " 23:59:59");	
		String unfreezeTime = DateHelp.dateTime();

		try {
			 List<BdPeriodfreeze> listFreeze = periodFreezeService.findList(start, end);
			 logger.info("查询到须解冻"+listFreeze.size()+"笔T+2周期冻结交易信息");
			 
			 for(int i=0;i<listFreeze.size();i++){
				 listFreeze.get(i).setIsfreeze("1");//状态 解冻
				 listFreeze.get(i).setProcdate(unfreezeTime);//解冻时间
			 }
			 periodFreezeService.updateList(listFreeze);
			 logger.info("今日成功解冻日期为"+lastdate+"的"+listFreeze.size()+"笔T+2交易信息");
			 
		} catch (Exception e) {
			logger.error("查询昨日T+2周期冻结信息列表出错", e);
			throw e;
		}
		
		//将昨日lastdate冻结的今日解冻
/*		try {
			BdPeriodfreeze periodfreeze = new BdPeriodfreeze();
			periodfreeze.setIsfreeze("1");//状态 解冻
			periodfreeze.setCreatedate(lastdate);//冻结时间
			periodfreeze.setProcdate(DateHelp.dateTime());//解冻时间
			periodFreezeService.updateFreezeState(periodfreeze);
			logger.info("对T+2商户交易信息执行解冻成功");
		} catch (Exception e) {
			logger.error("对T+2商户交易信息执行解冻时出错", e);
		}*/
		
	}
}
